package island.gotenyama.wand.web;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 全コントローラで共通的に処理されるInterceptor
 * 
 * @author tk
 */
public class AllRoundInterceptor extends HandlerInterceptorAdapter {

	/**
	 * LOGGER
	 */
	private static final Log LOG = LogFactory.getLog(AllRoundInterceptor.class);

	/**
	 * RequestHolder
	 */
	private static final ThreadLocal<HttpServletRequest> REQUEST_HOLDER = new ThreadLocal<HttpServletRequest>();
	
	/**
	 * ログ用文字列
	 */
	private static final String LOG_STRING = "***Interceptor ----> ";
	
	/**
	 * 
	 * 
	 * @return
	 */
	public static final HttpServletRequest getRequest() {
		return REQUEST_HOLDER.get();
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (LOG.isDebugEnabled()) {
			LOG.debug(LOG_STRING + "preHandle()");
		}
		REQUEST_HOLDER.set(request);
		response.setLocale(Locale.JAPANESE);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if (LOG.isDebugEnabled()) {
			LOG.debug(LOG_STRING + "postHandle()");
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (LOG.isDebugEnabled()) {
			LOG.debug(LOG_STRING + "afterCompletion()");
		}
		REQUEST_HOLDER.remove();
		
		String path = request.getRequestURI();
		if (path.endsWith(".xml")) {
			response.setContentType("application/xml; charset=utf-8");	
		}
	}
}
